package com.system.connect.springboot_flowers.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.connect.springboot_flowers.entity.Files;
import com.system.connect.springboot_flowers.mapper.FileMapper;
import com.system.connect.springboot_flowers.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yang
 * @since 2025-01-16
 */
@RestController
@RequestMapping("/api/file")
public class FileController {
    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Autowired
    private FileMapper fileMapper;

    /**
     * 文件上传接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public R<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            if (file == null || file.isEmpty()) {
                return R.error("文件不能为空");
            }

            System.out.println("Received file: " + file.getOriginalFilename());
            System.out.println("Content type: " + file.getContentType());
            System.out.println("File size: " + file.getSize());

            String fileName = file.getOriginalFilename();
            String type = FileUtil.extName(fileName);
            long size = file.getSize();
            
            //先存储到磁盘
            File uploadParentFile = new File(fileUploadPath);
            //判断配置的文件目录是否存在，不存在则产生一个新的文件目录
            if (!uploadParentFile.exists()) {
                boolean created = uploadParentFile.mkdirs();
                if (!created) {
                    return R.error("创建上传目录失败");
                }
            }
            //定义一个唯一文件标识码
            String uuid = IdUtil.fastSimpleUUID();
            String fileUuid = uuid + StrUtil.DOT + type;

            File uploadFile = new File(fileUploadPath + fileUuid);
            //把获取的文件存储到磁盘目录
            file.transferTo(uploadFile);
            // 修改URL路径，确保包含/api前缀
            String url = "/api/file/download?fileUuid=" + fileUuid;

            //存储数据库
            Files files = new Files();
            files.setName(fileName);
            files.setType(type);
            files.setSize(size);
            files.setUrl(url);
            fileMapper.insert(files);
            return R.success(url);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     *分页查询接口
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Files>> findPage(@RequestParam Integer pageNum,
                                   @RequestParam Integer pageSize){
//                                   @RequestParam(defaultValue = "") String name) {

        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete", false);
//        if (!"".equals(name)) {
//            queryWrapper.like("name", name);
//        }
        return R.success(fileMapper.selectPage(new Page<>(pageNum,pageSize),queryWrapper));
    }

//    @GetMapping("/{id}")
//    public R findOne(@PathVariable Integer id) {
//        Files files = fileMapper.selectById(id);
//        files.setIsDelete(true);
////        files.setIs_delete(true);
//        return R.success(fileMapper.updateById(files));
//    }

    /**
     * 下载接口
     */
    @GetMapping("/download")
    public void download(@RequestParam String fileUuid, HttpServletResponse response) {
        try {
            File file = new File(fileUploadPath + fileUuid);
            if (!file.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }

            // 根据文件类型设置Content-Type
            String contentType = "application/octet-stream";
            if (fileUuid.endsWith(".jpg") || fileUuid.endsWith(".jpeg")) {
                contentType = "image/jpeg";
            } else if (fileUuid.endsWith(".png")) {
                contentType = "image/png";
            } else if (fileUuid.endsWith(".gif")) {
                contentType = "image/gif";
            }
            response.setContentType(contentType);

            FileInputStream fileInputStream = new FileInputStream(file);
            ServletOutputStream outputStream = response.getOutputStream();

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}



